var vm = new Vue({
    el: '#app',  //选中整个main
    data: {
        user: '',
        recvAddrs: {},       //收货地址
        defaultAddrId: 1,
        addr: {
            area: '',
            phone: '',
            detailAddr: '',
            recvName: '',
        },
        defaultFlag: false,     //默认地址标志
        defaultAddr: '',          //默认地址信息
        myFavorteGoods: '',       //我的收藏
        showNum: sessionStorage.getItem("showNum"),
        orderList: {},              //待收货订单
        recvOrderList: {},          //已收货订单
        orderCount:'',               //订单数
        carCount:'',                 //添加购物车数量
        types: {},
        goodsName: ''
    },
    methods: {
        exitLogin:function(){
            axios.get("user/exitLogin").then(rs=>{
                sessionStorage.removeItem("user");
                sessionStorage.removeItem("showNum");
                sessionStorage.removeItem("typeId");
                layer.msg("退出登录成功！");
                location.href="index.html";
            });
        },
        //搜索，模糊查询
        search: function () {
            sessionStorage.setItem("typeId", 0);
            sessionStorage.setItem("goodsName", this.goodsName);
            location.href = 'productList.html';
        },
        //列表转换
        toGoodsListByType: function (typeId) {
            sessionStorage.setItem("typeId", typeId);
            sessionStorage.removeItem("goodsName");
            location.href = 'productList.html';
        },
        //获取商品列表
        getAllGoodsType: function () {
            axios.get('type/getAllGoodsType').then(rs => {
                this.types = rs.data.obj;
            });
        },
        getOrderCountByUserId:function(){
            axios.get(`order/getOrderCountByUserId/${this.user.id}`).then(rs => {
                this.orderCount = rs.data.obj.orderCount;
                this.carCount = rs.data.obj.carCount;
            })
        },
        //获取已收货的订单
        getRecvOrderByUserId:function(){
            axios.get(`order/getRecvOrderByUserId/${this.user.id}`).then(rs => {
                this.recvOrderList = rs.data.obj;
            })
        },
        //确认收货
        confirmReceipt:function(orderId){
            axios.put(`order/confirmReceipt/${orderId}`).then(rs => {
                layer.msg(rs.data.msg);
                sessionStorage.setItem("showNum",4);
                this.getPayedOrderByUserId();
                location.href='profile.html';
            });
        },
        //获取未收货的订单
        getPayedOrderByUserId: function () {
            axios.get(`order/getPayedOrderByUserId/${this.user.id}`).then(rs => {
                this.orderList = rs.data.obj;
            })
        },
        changeShow: function (num) {
            this.showNum = num;
            sessionStorage.setItem("showNum", num)
        },
        //商品详情
        toDetail: function (goods, event) {
            // event.preventDefault();
            axios.put(`goods/updateLookById/${goods.id}/${goods.look}`).then(rs => {
                goods.look = goods.look + 1;
                layer.msg(rs.data.msg);
                sessionStorage.setItem('goods', JSON.stringify(goods));
                location.href = 'goodsDetail.html';
            }).catch(e => {
                layer.msg(e.message)
            });
        },
        //获取我的收藏
        getAllFavorateGoods: function (start = 1, pageSize = 12) {
            axios.get(`goods/getAllFavorateGoods/${start}/${pageSize}/${this.user.id}`).then(rs => {
                this.myFavorteGoods = rs.data.obj;
            })
        },
        //更新用户信息
        updateUserInfo: function () {
            axios.post('user/updateUserInfo', this.user).then(rs => {
                layer.msg(rs.data.msg);
                sessionStorage.setItem("user", JSON.stringify(this.user));
            })
        },
        //图片上传
        uploadImg: function (e) {
            // let self = this;
            console.dir(e.target.files[0])
            let file = e.target.files[0];
            /* eslint-disable no-undef */
            let param = new FormData();  // 创建form对象
            param.append('upfile', file);  // 通过append向form对象添加数据
            // param.append('chunk', '0'); // 添加form表单中其他数据
            // console.log(param.get('file')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
            let config = {
                headers: {'Content-Type': 'multipart/form-data'}
            }
            // 添加请求头
            axios.post(`img/upload/${this.user.id}`, param, config)
                .then(res => {
                    if (res.data.success) {
                        this.user.pic = res.data.obj;
                        sessionStorage.setItem("user", JSON.stringify(this.user));
                        layer.msg(res.data.msg);
                        // location.href = "/html/user_look.html";
                    } else {
                        layer.msg(res.data.msg);
                    }
                })
        },
        findAllAddrByUserId: function () {
            axios.get(`recvAddr/findAllAddrByUserId/${this.user.id}`)
                .then(res => {
                    this.recvAddrs = res.data.obj;
                });
        },
        //修改默认地址
        changeDefalutAddr: function (addrId) {
            axios.put(`user/changeDefalutAddr/${this.user.id}/${addrId}`)
                .then(res => {
                    this.user.defaultAddrid = addrId;
                    this.defaultAddrId = addrId;
                    sessionStorage.setItem('user', JSON.stringify(this.user));
                    this.getDefaultAddr();
                    layer.msg('修改默认地址完成');
                });
        },
        //删除地址
        deleteAddrById: function (addrId) {
            layer.msg("是否删除地址？", {
                time: 0,      //表示不自动关闭
                btn: ['是', '否'],
                yes: (index)=> {
                    axios.delete(`recvAddr/deleteAddrById/${addrId}`)
                        .then(res => {
                            if (res.data.success) {
                                layer.msg(res.data.msg);
                                this.findAllAddrByUserId();
                                layer.close(index);
                            } else{
                                layer.msg(res.data.msg);
                                layer.close(index);
                            }
                        });
                },
            });
        },
        addAddr: function () {
            if (this.addr.recvName == '') {
                layer.msg("收货人不能为空！")
            } else if (this.addr.phone == '') {
                layer.msg("电话不能为空！")
            } else if (this.addr.area == '') {
                layer.msg("区域不能为空！")
            } else if (this.addr.detailAddr == '') {
                layer.msg("详细地址不能为空！")
            } else {
                axios.post(`recvAddr/addAddr/${this.defaultFlag}`, this.addr).then(rs => {
                    layer.msg(rs.data.msg);
                    if (this.defaultFlag) {
                        this.user.defaultAddrid = rs.data.obj;
                        this.defaultAddrId = rs.data.obj;
                        sessionStorage.setItem("user", JSON.stringify(this.user));
                        this.getDefaultAddr();
                    }
                    //刷新收货地址
                    this.findAllAddrByUserId(this.user.id);
                    this.addr = {};
                })
            }
        },
        getDefaultAddr: function () {
            axios.get(`recvAddr/getDefaultAddr/${this.user.id}/${this.defaultAddrId}`, this.addr).then(rs => {
                this.defaultAddr = rs.data.obj;
            })
        },
        mapInit: function () {
            let _this = this;
            $("#case3").bMap({
                name: "callback",
                callback: function (address, point) {
                    console.log(JSON.stringify(address));
                    let a = address.province + address.city + address.district + address.street + address.streetNumber + address.business;
                    _this.addr.area = a;
                    // console.log(_this.$data.addr.area);
                    _this.$nextTick(function () {
                        console.log(_this.addr.area);
                    });
                    // _this.getAllAddrs(a);
                }
            });
            $(".bMap #Map_input_callback").addClass("form__input");


            $(".user__img").click(function () {
                $(".uploadImg").click();
            });

            $(".table-address tr td button").on("click", function () {
                $(this).addClass("btn btn-danger");
                $(this).parents("tr").siblings().find("button").removeClass("btn btn-danger")
            });

            $(".del-address").on("click", function (ev) {
                var that = $(ev.target);
                $(".deleteSure").on("click", function () {
                    $('#deleteItemTip').modal('hide');
                    that.parents("tr").remove();
                })
            })

        },
        getUserInfo:function () {
            // debugger;
            let user = sessionStorage.getItem("user");
            if (user==''||user==undefined||user==null) {
                axios.get('user/getUserInfo').then(rs => {
                    debugger;
                    let user = rs.data.obj;
                    sessionStorage.setItem("user", JSON.stringify(user));
                    sessionStorage.setItem("showNum", 5);
                    sessionStorage.setItem("typeId", 0);
                    location.href = 'home.html';
                }).catch(e => {
                    layer.msg(e.message);
                })
            }
            this.user=JSON.parse(sessionStorage.getItem("user"));
            this.defaultAddrId=JSON.parse(sessionStorage.getItem("user")).defaultAddrid;
        }

    },
    created:function(){
        this.getUserInfo();
    },
    mounted: function () {
        this.findAllAddrByUserId();
        this.getDefaultAddr();
        this.mapInit();
        this.getAllFavorateGoods();
        this.getPayedOrderByUserId();
        this.getRecvOrderByUserId();
        this.getOrderCountByUserId();
        this.getAllGoodsType();
    },
});

